import * as CryptoJS from 'crypto-js'

const whiteListUrl = [
  'pages/login/index',
  'pages/hotelRegister/index',
  'pages/hotelRegister/register'
]

export function parseQueryStr(str: string) {
  const obj: any = {}
  str.split('&').forEach((item) => {
    const [key, value] = item.split('=')
    const newKey = key.replace(/^\[(.*)\]$/, '$1')
    obj[newKey] = decodeURIComponent(value)
  })
  return obj
}

/**
 *加密处理
 */
export const encryption = (params) => {
  const { data, type, param } = params
  let { key } = params
  const result = JSON.parse(JSON.stringify(data))
  if (type === 'Base64') {
    param.forEach((ele) => {
      result[ele] = btoa(result[ele])
    })
  } else {
    param.forEach((ele) => {
      const item = result[ele]
      key = CryptoJS.enc.Latin1.parse(key)
      const iv = key
      // 加密
      const encrypted = CryptoJS.AES.encrypt(item, key, {
        iv,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding
      })
      result[ele] = encrypted.toString()
    })
  }
  return result
}

export const isEmpty = (data: any) => {
  return data === undefined || data === null || data === ''
}

export const formatDate = (time: Date, fmt = 'yyyy-MM-dd HH:mm:ss') => {
  if (!(time instanceof Date)) return time
  const week = [
    '星期天',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六'
  ]
  const Q = ['一季度', '二季度', '三季度', '四季度']
  interface T {
    [key: string]: number | string
  }
  const o: T = {
    'M+': time.getMonth() + 1,
    'd+': time.getDate(),
    'H+': time.getHours(),
    'm+': time.getMinutes(),
    's+': time.getSeconds(),
    S: time.getMilliseconds(), // 毫秒
    q: Math.floor((time.getMonth() + 3) / 3), // 季度 (1)
    Q: Q[Math.floor((time.getMonth() + 3) / 3) - 1], // 季度 (一季度)
    w: time.getDay(), // 星期 (1)
    W: week[time.getDay()] // 星期 (星期天)
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      `${time.getFullYear()}`.substr(4 - RegExp.$1.length)
    )
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1
          ? `${o[k]}`
          : `00${o[k]}`.substr(`${o[k]}`.length)
      )
    }
  }
  return fmt
}

export const hidePhoneNumber = (phoneNumber: any) => {
  phoneNumber = phoneNumber.toString().trim()
  if (phoneNumber.length !== 11) {
    return phoneNumber
  }
  const hiddenPhoneNumber = `${phoneNumber.substr(
    0,
    3
  )}****${phoneNumber.substr(7)}`
  return hiddenPhoneNumber
}

// eslint-disable-next-line consistent-return
export function getEnvironment() {
  const accountInfo = wx.getAccountInfoSync()
  const { envVersion } = accountInfo.miniProgram
  // eslint-disable-next-line no-console
  console.log(accountInfo)
  if (envVersion === 'develop') {
    return 'dev'
  }
  if (envVersion === 'trial') {
    return 'qa'
  }
  if (envVersion === 'release') {
    return 'prod'
  }
}

export function redirectToLogin() {
  const pages = getCurrentPages()
  const currentPage: any = pages[pages.length - 1]
  if (currentPage && !whiteListUrl.includes(currentPage.route)) {
    uni.redirectTo({ url: '/pages/login/index' })
  }
}

export function generateUniqueRandomString(length = 40) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    let randomCharacter = characters.charAt(Math.floor(Math.random() * characters.length));
    // 确保每个随机字符在结果字符串中都是唯一的
    while (result.includes(randomCharacter)) {
      randomCharacter = characters.charAt(Math.floor(Math.random() * characters.length));
    }
    result += randomCharacter;
  }
  return result;
}
